<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import { InfoFilled } from '@element-plus/icons-vue'
import type { StatisticalIndicator } from '@/types/modules/statistical-indicator'

import { uuid } from '@/utils'
import { selectUnitList } from '@/api/modules/unitManagement'
import { useMixinQueryIndicatorDicts } from '@/mixins/MixinQueryIndicatorDicts'

const info = defineModel<StatisticalIndicator>({
  required: true,
})
const formRef = ref<FormInstance>()
const rules = computed<FormRules>(() => {
  const pointCode = unref(info).pointCode ?? ''
  return {
    pointName: [
      { required: true, message: '请选择用能单元' },
    ],
    indicatorName: [
      { required: true, message: '请选择或输入指标名称' },
      { min: 2, max: 30, message: '长度在 2 到 30 个字符' },
    ],
    indicatorNumber: [
      { required: true, message: '请输入指标编码' },
      {
        min: pointCode.length + 2,
        max: 30,
        message:
          `长度在 ${
          pointCode.length + 2
          } 到 30 个字符`,
      },
    ],
    unitId: [
      { required: true, message: '请选择计量单位' },
      {
        validator(_rule: any, value: any, callback: (e?: any) => void) {
          if (value > 0) {
            callback()
          }
          else {
            callback(new Error('请选择计量单位'))
          }
        },
      },
    ],
  }
})
const [unitList, setUnitList] = useShallowState<any[]>([])

const inputable = ref(false)
watch(() => unref(inputable), () => {
  unref(info).indicatorName = ''
})

function handleUnitChange(unitId: any) {
  const list = unref(unitList)
    .map(item => item.unitList)
    .flat()
  const unit = list.find(item => item.id === unitId)
  if (!unit)
    return
  info.value.unitExpression = unit.unitExpression
  info.value.unitName = unit.unitName
}

async function getUnitList() {
  try {
    const res = await selectUnitList()
    setUnitList((res.data || []).map((v: any) => ({
      ...v,
      id: uuid(),
    })))
  }
  catch (e) {}
}

async function validate() {
  return formRef.value?.validate()
}
async function resetFields() {
  formRef.value?.resetFields()
}

const {
  indicatorDicts,
  getIndicatorDicts,
  getKeyFromValue,
} = useMixinQueryIndicatorDicts()

function handleIndicatorNameChange(val: any) {
  if (val) {
    const key = getKeyFromValue(val)
    if (key) {
      const pointCode = unref(info).pointCode ?? ''
      info.value.indicatorNumber = `${pointCode}.${key}`
    }
  }
}

onMounted(() => {
  getUnitList()
  getIndicatorDicts()
})

defineExpose({
  validate,
  resetFields,
})
</script>

<template>
  <ElForm
    ref="formRef"
    :model="info"
    :rules="rules"
    label-width="100px"
    class="indicator-basis-form"
    label-suffix="："
    status-icon
  >
    <ElFormItem label="用能单元">
      <div>
        {{ info.pointName }}
        <span v-if="info.pointCode">
          （{{ info.pointCode }}）
        </span>
      </div>
    </ElFormItem>
    <ElFormItem label="指标名称" prop="indicatorName" class="indicator-name-form-item">
      <IndicatorNamePicker
        v-model="info.indicatorName"
        :options="indicatorDicts"
        style="width: 100%"
        placeholder="请选择或输入指标名称"
        @change="(val: any) => handleIndicatorNameChange(val)"
      />
    </ElFormItem>
    <ElFormItem label="指标编码" prop="indicatorNumber">
      <ElInput
        v-model="info.indicatorNumber"
        placeholder="请输入指标编码"
        :maxlength="50"
        :minlength="2"
      />
    </ElFormItem>
    <ElFormItem label="计量单位" prop="unitId">
      <ElCascader
        v-model="info.unitId"
        :options="unitList"
        class="width-fill"
        :props="{
          label: 'unitName',
          value: 'id',
          children: 'unitList',
          emitPath: false,
        }"
        @change="handleUnitChange"
      />
    </ElFormItem>
    <ElFormItem>
      <template #label>
        <ElTooltip placement="top" content="取消填写采集点点位后，请更新对应的数据存储的选择。">
          <div class="align-center flex">
            采集点点位<ElIcon><InfoFilled /></ElIcon>
          </div>
        </ElTooltip>
      </template>
      <ElInput
        v-model="info.indicatorCode"
        placeholder="请输入采集点点位"
        :maxlength="20"
        :minlength="2"
      />
    </ElFormItem>
  </ElForm>
</template>

<style lang="scss" scoped>
.indicator-basis-form {
  max-width: 600px;
  :deep(.el-form-item__error) {
    left: 100%;
    top: 50%;
    white-space: nowrap;
    transform: translate(10px, -50%);
  }
}
.indicator-name-form-item {
  :deep(.el-form-item__error) {
    top: 15px !important;
  }
}
</style>
